package com.webserver.core;

import com.webserver.http.HttpServletRequest;

import java.io.*;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

/*
线程任务
负责与特定的客服进行HTTP交互
 */
public class ClientHandler implements Runnable {
    private Socket socket;//提升作用域

    public ClientHandler(Socket socket) {//重写构造方法
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            //http：//localhost:8088
            //1解析请求（请求头，消息头，消息正文）
            HttpServletRequest request = new HttpServletRequest(socket);//高内聚低耦合思想


            //2处理请求--通过request获取请求
            String path = request.getUri();
            //3发送响应
            //将./webapps/myweb/index.html响应给浏览器
            File file = new File("./webapps"+path);
            /*
            响应的大致内容:
                    HTTP/1.1 200 OK(CRLF)
                    Content-Type: text/html(CRLF)
                    Content-Length: 2546(CRLF)(CRLF)
                    1011101010101010101......
             */
            OutputStream out = socket.getOutputStream();
            //3.1发送状态行
            String line = "HTTP/1.1 200 OK";
            byte[] data = line.getBytes("ISO8859-1");
            out.write(data);
            out.write(13);//发送一个回车符
            out.write(10);//发送一个换行符

            //3.2发送响应头
            line = "Content-Type: text/html";
            data = line.getBytes("ISO8859-1");
            out.write(data);
            out.write(13);//发送一个回车符
            out.write(10);//发送一个换行符

            line = "Content-Length: "+file.length();
            data = line.getBytes("ISO8859-1");
            out.write(data);
            out.write(13);
            out.write(10);

            out.write(13);
            out.write(10);

            FileInputStream fis = new FileInputStream(file);//读取到拼接好路径的那个文件----一个资源相当于一个应用
            //固定写法，遇到不止一次---读多少写多少---阻塞方法
            int len;
            byte[] buf = new byte[1024 * 10];
            while ((len =fis.read(buf)) != -1){
                out.write(buf,0,len);//读取buf  0开始   len结束
            }
            System.out.println("响应发送完毕！");//意味着


        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();//响应后断开连接
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


}
